import httpFetch from 'share/httpFetch';
import config from 'config';
import errorMessage from 'share/errorMessage';
import { deepFullCopy, messages } from "share/common";
import configureStore from 'stores';
import FRDEService from 'containers/data-center/report/travel-report/personnel-fee-report/data-transfer.service';
import RSCService from 'containers/data-center/report/travel-report/report-search-components.service';
import React from "react";
import axios from 'axios';


// 很奇怪的东西，这种拦截器如果真有必要的话，直接让后端拼好不行吗？
// http响应拦截器
axios.interceptors.response.use(data => {
  let dataAfterTask13509 = fixTask17073(data);
  return dataAfterTask13509
}, error => {
  return Promise.reject(error)
});

//账套把币种加上
function fixTask17073(data) {
  if (data.config.url.match('/api/setOfBooks/query/dto') && data.data && data.data.length) {
    if (data.data[0].setOfBooksName_functionalCurrencyCode !== undefined) {
      return data;
    }
    data.data.map((item) => {
      item.setOfBooksName_functionalCurrencyCode = item.setOfBooksName + "/" + item.functionalCurrencyCode;
    })
  }
  return data;
}


/**
 * 这个文件仅用于接口调用及部分数据处理
 * 报表数据处理在data-transfer中
 *
 * 代码从原来的费用分析表中copy过来修改的
 * 实在是没时间优化
 * 后面有空直接重构了
 */

const current = new Date();
let searchFormDefaultList = [
  //账套(单选)
  {
    single: true,
    type: 'list',
    id: 'filterSetOfBooksId',
    event: "books",
    defaultValue: [],
    label: messages('data-center.key73')/*账套(单选)*/,
    listType: 'select_set_of_books',
    labelKey: 'setOfBooksName_functionalCurrencyCode',
    valueKey: 'setOfBooksId',
    placeholder: messages('data-center.key27')/*请选择*/,
    disabled: true
  },
  //日期类型
  {
    single: true,
    type: 'select',
    id: 'filterDateType',
    event: 'filterDateType',
    label: messages('data-center.key143')/*日期类型*/,
    defaultValue: "0",  // 费用发生日期
    options: [{
      value: "0",
      label: messages('data-center.key144')/*费用发生日期*/
    }],
    allowClear: false,
    placeholder: messages('data-center.key78')/*请先选择账套选择*/,
  },
  //年(单选)
  {
    type: 'select',
    id: 'filterYear',
    label: messages('data-center.key74')/*年(单选)*/,
    defaultValue: current.getFullYear(),
    options: [],
    placeholder: messages('data-center.key27')/*请选择*/,
  },
  //月(多选)
  {
    type: 'multiple',
    id: 'filterYearMonths',
    label: messages('data-center.key75')/*月(多选)*/,
    options: [],
    placeholder: messages('data-center.key27')/*请选择*/,
  },
  //报销类型(多选)(有依赖)
  {
    type: 'multiple',
    id: 'filterFormOids',
    label: messages('data-center.key81')/*报销单类型(多选)*/,
    options: [],
    placeholder: messages('data-center.key78')/*请先选择账套选择*/,
  },
  //报销单状态（多选）
  {
    type: 'multiple',
    id: 'filterStatus',//根据后端赋值，这是写默认的会重新覆盖
    label: messages('data-center.key92')/*报销单状态(多选)*/,
    options: [],//需要从后端请求，引用传递
    placeholder: messages('data-center.key27')/*请选择*/,
  },
  //费用类型(多选)(有依赖)
  {
    type: 'multiple',
    id: 'filterExpenseTypeIds',
    label: messages('data-center.key83')/*费用类型(多选)*/,
    options: [],
    placeholder: messages('data-center.key78')/*请先选择账套选择*/,
  },
];
export default {
  dataFactory: {
    //  key 要与搜索组件的 id 一致
    filterYear: [],
    filterYearMonths: [],
    filterFormOids: [],
    filterStatus: [],
    filterExpenseTypeIds: [],
    filterDateType: []
  },
  vendorCache: {
    filterFormOids: {
      value: "0000",
      label: messages('data-center.key84')/*消费商(公司支付)*/
    },
    filterStatus: {}
  },
  searchForm: [],
  getSearchFormItemById(id, searchForm) {
    let length = searchForm.length,
      i = 0;
    while (i++ < length) {
      if (searchForm[i] === id) {
        return searchForm[i]
      }
    }
  },
  getDefaultValueById(id, searchForm) {
    let val = [ {} ];
    searchForm.map(item => {
      if (item.id === id) {
        val = item.defaultValue
      }
    });
    return val;
  },
  getAllDataBySearchParams(searchParams, shouldGetList, isClickSearch, pagination) {
    /*
    * 通过 searchParams 控制查询图表
    * 一共四个图表
    * 可以查询其中任意几个
    * */
    let _this = this;
    let allTypeFunctions = {
      'expenseTendencyReport': _this.getExpenseAnalysisReport,
      'expenseTypeReport': _this.getReportDetailExpenseType,
      'statusAmountReport': _this.getReportDetailReportStatus,
    }
    //查询报表类型对应的参数
    let allTypeParams = {
      "expenseTendencyReport": "filterYearMonths",
      "expenseTypeReport": "filterExpenseTypeIds",
      "statusAmountReport": "filterStatus",
    }
    let getList = shouldGetList.map(item => {
      let cacheParams = deepFullCopy(searchParams);
      /*
      * 查询的时候，要注意，过滤报表自身的参数需要删除
      * 比如 查询报销单状态 的参数是 filterStatus；
      * 那么在 查询报销单状态 的时候 就需要删除 filterStatus参数；
      * 由于图表直接相互点击，存在数据请求，所以，如果点击图表进行搜索，那么页面上方的搜索条件就不要传，
      * 否则存在矛盾---图表搜索与页面搜索不知道该选择哪一个
      * */
      if (!isClickSearch) {
        //如果是点击搜索按钮，不过滤
        cacheParams[allTypeParams[item]] = undefined;
      }
      return allTypeFunctions[item](cacheParams);
    })
    return Promise.all(getList);

  },


  // 个人费用总体趋势报表查询接口：
  getExpenseAnalysisReport(params) {
    // {
    //   "reportId":10010
    //   // 还有的筛选器条件
    // }
    return new Promise((resolve, reject) => {
      httpFetch.post(config.baseUrl + '/report/api/personal/expense/analysis/report/total', params)
        .then((response) => {
          let res = {};
          let data = response.data;
          //兼容性处理
          res.expenseTendencyReport = data.expenseTendencyReport || [];
          res.expenseTendencyReportOptions = FRDEService.expenseTendencyReport(res.expenseTendencyReport);
          res.baseAmount = data.baseAmount;
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  // 人员费用明细接口：
  getReportDetailUserDetailExpense(params, pagination) {
    // {
    //   "reportId":10010
    //   // 还有的筛选器条件
    // }
    return new Promise((resolve, reject) => {
      httpFetch.post(config.baseUrl + '/report/api/personal/expense/analysis/report/detail/list' +
        '?page=' + pagination.page + "&size=" + pagination.size, params)
        .then((response) => {
          resolve(response);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },

  // 获取费用分析报表明细-费用类型图表
  getReportDetailExpenseType(params) {
    // {
    //   "reportId":10010
    //   // 还有的筛选器条件
    // }
    return new Promise((resolve, reject) => {
      httpFetch.post(config.baseUrl + '/report/api/personal/expense/analysis/report/expense/type', params)
        .then((response) => {
          let res = {};
          let data = response.data;
          //兼容性处理
          res.expenseTypeReport = data ? data : [];
          res.expenseTypeReportOptions = FRDEService.expenseTypeReport(data);
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  // 获取费用分析报表明细-报销状态图表
  getReportDetailReportStatus(params) {
    // {
    //   "reportId":10010
    //   // 还有的筛选器条件
    // }
    return new Promise((resolve, reject) => {
      httpFetch.post(config.baseUrl + '/report/api/personal/expense/analysis/report/status', params)
        .then((response) => {
          let res = {};
          let data = response.data;
          //兼容性处理
          res.statusAmountReport = data ? data : [];
          res.statusAmountReportOptions = FRDEService.statusAmountReport(data);
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },

  //设置账套
  getSetOfBooksIdFeeReportDefaultValue() {
    let companyFromFeeReport = configureStore.store.getState().login.company;
    let { setOfBooksId } = companyFromFeeReport;
    let obj = {
      setOfBooksName_functionalCurrencyCode: companyFromFeeReport.setOfBooksName + "/" + companyFromFeeReport.baseCurrency,
      setOfBooksId
    };
    this.searchForm.map(item => {
      if (item.id === "filterSetOfBooksId") {
        item.defaultValue = [ obj ]
      }
    })

    this.getExpenseTypeListByBooksID(setOfBooksId);
    this.getFilterFormOidsByBooksID(setOfBooksId);
  },
  //设置年
  getValueYear(from, to) {
    this.dataFactory.filterYear.length = 0;
    for (let i = to; i >= from; i--) {
      let o = {
        value: i,
        label: i
      };
      this.dataFactory.filterYear.push(o)
    }
    this.fieldOptionsSetter("filterYear");
  },
  // 设置月
  getValueMonth(from, to) {
    this.dataFactory.filterYearMonths.length = 0;
    for (let i = from; i <= to; i++) {
      let o = {
        value: i,
        label: i
      };
      this.dataFactory.filterYearMonths.push(o)
    }
    this.fieldOptionsSetter("filterYearMonths");
  },
  //报销单状态
  getERStatus() {
    RSCService.getSystemValueList(5030)
      .then(res => {
        let list = res.data.values;
        this.getFilterStatus(list);
      })
  },
  getDateTypeFilter() {
    RSCService.getSystemValueList(5037)
      .then(res => {
        let list = res.data.values || [];
        this.dataFactory.filterDateType = list.map(item => {
          let { value, messageKey: label } = item;
          return {
            value,
            label
          }
        });
        this.fieldOptionsSetter("filterDateType");
      })
  },
  //费用类型
  getFilterExpenseTypeIds(list) {
    this.dataFactory.filterExpenseTypeIds.length = 0;
    list.map(item => {
      let data = {};
      data.value = item.id;
      data.label = item.name;
      this.dataFactory.filterExpenseTypeIds.push(data);
    });
    this.fieldOptionsSetter("filterExpenseTypeIds");
  },
  //报销类型
  getFilterFormOids(list, dataType) { // 传入dataType表示需要根据当前日期类型判断是否加入消费商公司支付
    let {filterFormOids} = this.vendorCache;
    if (dataType !== undefined) {
      list = this.dataFactory.filterFormOids;

      if (dataType === "0") {
        if (!list.includes(filterFormOids)) {
          list.push(filterFormOids)
        }
      } else {
        let index = list.indexOf(filterFormOids);
        if (index !== -1) {
          list.splice(index, 1)
        }
      }
    } else {
      this.dataFactory.filterFormOids.length = 0;
      list.map(item => {
        let data = {};
        data.value = item.formOID;
        data.label = item.formName;
        this.dataFactory.filterFormOids.push(data);
      });

      // 静态额外的值，可能会改值
      this.dataFactory.filterFormOids.push(filterFormOids);
    }
    this.fieldOptionsSetter("filterFormOids");

  },
  // 报销状态
  getFilterStatus(list, dataType) { // 传入dataType表示需要根据当前日期类型进行筛选
    if (dataType !== undefined) {
      let {filterStatus} = this.vendorCache;
      list = this.dataFactory.filterStatus;
      if (dataType === "0") {
        if (!list.includes(filterStatus)) {
          list.push(filterStatus)
        }
      } else {
        let index = list.indexOf(filterStatus);
        if (index !== -1) {
          list.splice(index, 1)
        }
      }
    } else {
      this.dataFactory.filterStatus.length = 0;
      list.forEach(item => {
        let data = {};
        data.value = item.value;
        data.label = item.messageKey;
        this.dataFactory.filterStatus.push(data);
        if (data.value === "0000") {
          this.vendorCache.filterStatus = data;
        }
      });
    }
    this.fieldOptionsSetter("filterStatus");
  },
  //得到账套下所有费用类型(有依赖)
  getExpenseTypeListByBooksID(setOfBooksId) {
    let params = {
      page: 0,
      size: 1000,
      setOfBooksId
    };
    return new Promise((resolve, reject) => {
      httpFetch.get(`${config.baseUrl}/api/expense/type/by/setOfBooks`, params)
        .then((response) => {
          let list = response.data;
          this.getFilterExpenseTypeIds(list);
          resolve(response)
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  //得到账套下所有 报销类型(有依赖)
  getFilterFormOidsByBooksID(setOfBooksId) {
    let params = {
      page: 0,
      size: 1000,
      setOfBooksId,
      // valid: false, 启用还是禁用，全部不传
      formTypeList: [ 3001, 3002, 3003 ]
    };
    return new Promise((resolve, reject) => {
      httpFetch.get(`${config.baseUrl}/api/custom/forms/setOfBooks/all`, params)
        .then((response) => {
          let list = response.data;
          this.getFilterFormOids(list);
          resolve(response)
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        })
    })
  },
  fieldOptionsSetter(fieldKey) {
    this.searchForm.map(item => {
      if (item.id === fieldKey) {
        item.placeholder = messages('data-center.key27')/*请选择*/;
        item.options = this.dataFactory[fieldKey]
      }
    })
  },
  //获取费用报表的搜索组件
  getFeeReportSearchForm() {
    // return new Promise((resolve, reject) => {
    //   resolve(this.searchForm);
    // })
    return this.searchForm
  },
  //初始化搜索组件数据
  InitSearchComponents() {
    this.searchForm = deepFullCopy(searchFormDefaultList);
    let tenantFromFeeReport = configureStore.store.getState().login.tenant;
    let startTime = (new Date(tenantFromFeeReport.createdDate)).getFullYear();
    let endTime = current.getFullYear();
    return Promise.all([
      this.getSetOfBooksIdFeeReportDefaultValue(),
      this.getValueYear(startTime, endTime),
      this.getValueMonth(1, 12),
      //报销单状态
      this.getERStatus(),
      this.getDateTypeFilter()
    ])
  },
  //检测是不是点击的同一个项目
  checkTheSameItemAndAdd(list, type, option, params) {
    let criteria = null, index = 0;
    if (type === "expenseTendencyReport") {
      criteria = parseInt(params.data.month);
    } else {
      criteria = params.data.criteria;
    }
    for (let i = 0; i < list.length; i++) {
      if (type === list[i].type) {
        index = i;
      }
    }
    if (type === "expenseTendencyReport") {
      if (list[index].params.month !== criteria) {
        list[index].option = option;
        list[index].params = params;
      }
    } else {
      if (list[index].params.data !== criteria) {
        list[index].option = option;
        list[index].params = params;
      }
    }
    return list;
  },
  checkHasCTS(list, type) {
    for (let i = 0; i < list.length; i++) {
      if (type === list[i].type) {
        return true;
      }
    }
  },
  /*
  * 点击的图表类型加入队列
  * @params list 点击的队列
  * @params type 点击的图表类型
  * @params option 点击的图表类型显示的数据
  * @params params 点击的参数 eg: 机票,滴滴出行
  * */
  addCTS(list, type, option, params) {
    let obj = {
      type,
      option,
      params
    }
    if (this.checkHasCTS(list, type)) {
      /*
      * 还需要检测同一种类型中的不同项目
      * 都是费用类型，第一次点击的是滴滴出行，第二次点击的是机票
      * 就需要用 机票 换成 滴滴出行
      * */
      return this.checkTheSameItemAndAdd(list, type, option, params);
    } else {
      list.push(obj);
      return list;
    }
  },
  //删除点击的图表类型数据
  deleteCTS(list, type) {
    return list.filter(item => {
      return (type !== item.type)
    })
  },
  //点击搜索按钮重置数据
  resetStyle(allData) {
    allData["expenseTendencyReport"]["expenseTendencyReport" + "Options"].series[0].itemStyle = null;
    allData["expenseTypeReport"]["expenseTypeReport" + "Options"].series[0].itemStyle = null;
    allData["statusAmountReport"]["statusAmountReport" + "Options"].series[0].color = null;
    return allData;
  },
  //根据响应结果+被点击过的图表
  //设置激活的柱子的颜色，对于成本中心特殊处理
  getCanRenderAllDateByApiRes(res, CTS) {
    let allData = {};
    res.map(item => {
      for (let key in item) {
        if (Object.prototype.toString.call(item[key]) === "[object Array]") {
          allData[key] = item;
          if (this.findActiveKey(key, CTS)) {
            let params = this.findActiveKey(key, CTS).params;

            let activeIndex = this.getNewParamsByOldParams(allData[key][key + "Options"], params, key);
            let length = allData[key][key + "Options"].series[0].data.length;
            switch (key) {
              case "expenseTendencyReport": {
                allData[key][key + "Options"].series[0].itemStyle = FRDEService.getActiveItemStyle(activeIndex, length)
                break
              }
              case "expenseTypeReport": {
                allData[key][key + "Options"].series[0].itemStyle = FRDEService.getActiveItemStyle(activeIndex, length)
                break
              }
              case "statusAmountReport": {
                allData[key][key + "Options"].series[0].color = FRDEService.getBarOptionsColors(activeIndex, length)
                break
              }
            }

          }
        } else if (key === "baseAmount") {
          allData[key] = item[key];
        }
      }
    });
    return allData;
  },
  //判断图表中是否有被点击的项目，如果有，返回这个项目
  findActiveKey(key, CTS) {
    if (CTS.length) {
      for (let i = 0; i < CTS.length; i++) {
        if (key === CTS[i].type) {
          return CTS[i]
        }
      }
    }
  },

  //找到被激活的数据，比如点击了部门，就要返回部门的序号
  getNewParamsByOldParams(data, oldParams, type) {
    let criteria = oldParams.data.criteria;
    if (type === "expenseTendencyReport") {
      criteria = parseInt(oldParams.data.month);
    }
    let arr = data.series[0].data;
    if (arr.length) {
      for (let i = 0; i < arr.length; i++) {
        if (type === "expenseTendencyReport") {
          if (criteria === arr[i].month) {
            return i
          }
        } else {
          if (criteria === arr[i].criteria) {
            return i
          }
        }
      }
    }
  },


}
